package com.example.customview.progressview

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.View

class ProgressView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null,
    defaultIndex: Int = 0
) :
    View(context, attributeSet, defaultIndex) {
    private var mPaint = Paint()
    private var mTextPaint = Paint()
    private var percent = 0.0

    companion object{
        const val TAG ="ProgressView"
    }

    init {
        mPaint.color = Color.BLUE
        mPaint.style = Paint.Style.FILL_AND_STROKE
        mTextPaint.color = Color .WHITE
        mTextPaint.style = Paint.Style.STROKE
        setBackgroundColor(Color.GRAY)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        var path = Path()
        var topY = ((1-percent)*height).toFloat()
        path.moveTo(0f,topY)
        path.lineTo(width.toFloat(),topY)
        path.lineTo(width.toFloat(),height.toFloat())
        path.lineTo(0f,height.toFloat())
        canvas?.drawPath(path,mPaint)


        var content = "${percent*100} %"
        val measureText = mTextPaint.fontMetrics
        var baseLine = height/2-(measureText.ascent+measureText.descent)/2

        val textWidth = mTextPaint.measureText(content)
        canvas?.drawText(content,width/2-textWidth/2,baseLine,mTextPaint)

    }

    fun start(percent: Double) {
       this.percent = percent
        postInvalidate()
    }

}